package cn.edu.zut.controller;

import cn.edu.zut.domain.User;
import cn.edu.zut.service.UserService;
import cn.edu.zut.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService service;

    @RequestMapping("/findByUserName.do")
    public @ResponseBody User findByUserName(String userName) {
        System.out.println(userName);
        User user = service.findByUserName(userName);
        return user;
    }

    @RequestMapping("/insert.do")
    public @ResponseBody String insert(@RequestBody User user) {
        if(user.getNickName().length() == 0) {
            user.setNickName(user.getUserName());
        }
        System.out.println(user);
        String res = "";
        if(user.getUserName().length() != 12) {
            res = "STNumber Error";
        } else if (service.findByUserName(user.getUserName()) != null){
            res = "STNumber Exist";
        } else if (user.getPasswd().length() < 6) {
            res = "passWd Short";
        } else {
            user.setPasswd(MD5Utils.md5(user.getPasswd()));
            service.insert(user);
            res = "Insert Success";
        }
        return res;
    }

    @RequestMapping("/update.do")
    public @ResponseBody void update(@RequestBody User user) {
        System.out.println(user);
        service.update(user);
    }

    @RequestMapping("/findAll.do")
    public @ResponseBody List<User> findAll() {
        return service.findAll();
    }

    @RequestMapping("/findAllUsers.do")
    public @ResponseBody List<User> findAllUsers() {
        return service.findAllUsers();
    }

    @RequestMapping("/deleteByUserName.do")
    public @ResponseBody void deleteByUserName(String userName) {
        System.out.println(userName);
        service.deleteByUserName(userName);
    }

    @RequestMapping("/findByLikeUserName.do")
    public @ResponseBody List<User> findByLikeUserName(@RequestBody User user) {
        System.out.println(user);
        return service.findByLikeUserName(user);
    }

    @RequestMapping("/findPart.do")
    public @ResponseBody List<User> findPart(String offset, String maxNumber) {
        return service.findPart(Integer.parseInt(offset), Integer.parseInt(maxNumber));
    }

}
